

package tomkitty;

import java.util.*;
import java.io.*;
import java.lang.reflect.*;

public class TkEvents {

  protected static final Hashtable<Class, Vector<EventListener>> listeners
    = new Hashtable<Class, Vector<EventListener>>();

  public static void addListener(EventListener listener, Object payload) {

    Class payloadClass = payload.getClass();

    Vector<EventListener> plisteners = listeners.get(payloadClass);

    if (plisteners == null) {
      plisteners = new Vector<EventListener>();
      listeners.put(payloadClass, plisteners);
    }

    plisteners.add(listener);
  }

  protected static void removeListener(EventListener listener, Object payload) {
    Class payloadClass = payload.getClass();
    Vector<EventListener> plisteners = listeners.get(payloadClass);

    if (plisteners != null) {
      plisteners.remove(listener);
    }
  }

  public static void onEvent(Object source, Object payload) {
    Class payloadClass = payload.getClass();
    Vector<EventListener> plisteners = listeners.get(payloadClass);

    if (plisteners != null) {
      for (Enumeration<EventListener> e = plisteners.elements(); 
           e.hasMoreElements();) {
        EventListener l = e.nextElement();
        if (! l.onEvent(source, payload)) {
          removeListener(l, payload);
        }
      }
    }
  }

}
